﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.OleDb;
using System.Collections;
using StateGrid.MDBservice;
using System.IO;
using iTextSharp.text.pdf;

namespace StateGrid.NYBG
{
    class NYBG_MDB : MDBservice.MDBservice
    {
        public override String id
        {
            get
            {
                return "nengyuanbaogao";
            }
        }

        private NYBG_DAO nybgDAO = new NYBG_DAO();

        public override void clear()
        {
            base.clear();
        }

        public override String getTest()
        {
            IList<NYBG_FL> r = nybgDAO.GetAllNYBG_FL();
            String ret = String.Empty;
            foreach (NYBG_FL i in r)
            {
                ret += i.ToString();
            }
            return ret;
        }

        public NYBG_MDB()
        {
            pmTableName = "NYBG_WF";
            formatPmTableName = "NYBG";
            title = "能源报告";
        }

        public override void setColumnList()
        {
            this.ColumnList = new List<Column>();
            if (hasFormatTable)
            {
                this.ColumnList.Add(new Column("分类编码", OleDbType.WChar, 10));
                this.ColumnList.Add(new Column("索引编码", OleDbType.WChar, 50));
                this.ColumnList.Add(new Column("文件名", OleDbType.WChar, 20));
                this.ColumnList.Add(new Column("页数", OleDbType.SmallInt));
                this.ColumnList.Add(new Column("报告名称", OleDbType.WChar, 255));
                this.ColumnList.Add(new Column("年份", OleDbType.WChar, 4));
                this.ColumnList.Add(new Column("出版日期", OleDbType.Date));
                this.ColumnList.Add(new Column("作者", OleDbType.WChar, 254));
                this.ColumnList.Add(new Column("作者单位", OleDbType.WChar, 200));
                this.ColumnList.Add(new Column("主办单位", OleDbType.WChar, 0));
                this.ColumnList.Add(new Column("主题词", OleDbType.WChar, 200));
                this.ColumnList.Add(new Column("文摘", OleDbType.WChar, 0));
                this.ColumnList.Add(new Column("报告号", OleDbType.WChar, 50));
                this.ColumnList.Add(new Column("分类体系", OleDbType.WChar, 10));
                this.ColumnList.Add(new Column("子分类", OleDbType.WChar, 200));
                this.ColumnList.Add(new Column("文献编号", OleDbType.WChar, 30));
                this.ColumnList.Add(new Column("原文件名", OleDbType.WChar, 50));
                this.ColumnList.Add(new Column("全文", OleDbType.Boolean));
                this.ColumnList.Add(new Column("更新日期", OleDbType.Date));
            }
            else
            {
                //未支持
            }
        }

        protected override PM getPM(OleDbDataReader reader, out String err)
        {
            err = String.Empty;
            NYBG_PM pm = new NYBG_PM();
            if (hasFormatTable)
            {
                pm.flbm = reader["分类编码"].ToString().Trim();
                pm.sybm = reader["索引编码"].ToString().Trim();
                pm.wjm = reader["文件名"].ToString().Trim();
                try
                {
                    pm.ys = int.Parse(reader["页数"].ToString());
                }
                catch (Exception)
                {
                    pm.ys = 0;
                    err += pm.sybm + ":" + pm.bgmc + ": 页数\"" + reader["页数"] + "\"出错，置为0\n";
                }
                pm.bgmc = reader["报告名称"].ToString().Trim();
                try
                {
                    pm.nf = int.Parse(reader["年份"].ToString());
                }
                catch (Exception)
                {
                    pm.nf = 0;
                    err += pm.sybm + ":" + pm.bgmc + ": 年份\"" + reader["年份"] + "\"出错，置为0\n";
                }
                try
                {
                    if (String.Empty.Equals(reader["出版日期"].ToString().Trim()))
                    {
                        err += pm.flbm + ":" + pm.bgmc + ":出版日期为空\n";
                        pm.cbrq = DateTime.Parse(pm.nf.ToString() + "/1/1");
                    }
                    else
                        pm.cbrq = DateTime.Parse(reader["出版日期"].ToString().Trim());
                }
                catch
                {
                    err += pm.flbm + ":" + pm.bgmc + ": 出版日期\"" + reader["出版日期"] + "\"出错\n";
                }
                pm.zz = reader["作者"].ToString().Trim();
                pm.zzdw = reader["作者单位"].ToString().Trim();
                pm.zbdw = reader["主办单位"].ToString().Trim();
                pm.ztc = reader["主题词"].ToString().Trim();
                pm.wz = reader["文摘"].ToString().Trim();
                pm.bgh = reader["报告号"].ToString().Trim();
                pm.fltx = reader["分类体系"].ToString().Trim();
                pm.zfl = reader["子分类"].ToString().Trim();
                pm.wxbh = reader["文献编号"].ToString().Trim();
                pm.ywjm = reader["原文件名"].ToString().Trim();
            }
            else
            {
                //不支持
            }
            pm.dlr = user.name;
            pm.fillEmptyStringAsNull();
            return pm;
        }

        public override bool checkPMValid(PM pm, out string errMsg)
        {
            errMsg = String.Empty;
            NYBG_PM nybg = (NYBG_PM)pm;
            this.openOleDbConnection();
            sqlcmd.CommandText = @"select * from " + formatPmTableName + " where 年份=@年份 and 报告名称=@报告名称 and 作者=@作者";
            sqlcmd.Connection = this.ObjConnection;
            sqlcmd.Parameters.Add(new OleDbParameter("年份", nybg.nf));
            sqlcmd.Parameters.Add(new OleDbParameter("报告名称", nybg.bgmc));
            sqlcmd.Parameters.Add(new OleDbParameter("作者", nybg.zz));
            OleDbDataReader reader = sqlcmd.ExecuteReader();

            if (reader.Read())
            {
                reader.Close();
                sqlcmd.Parameters.Clear();
                return true;
            }
            else
            {
                reader.Close();
                sqlcmd.Parameters.Clear();
                return false;
            }
            //            this.closeOleDbConnection();
        }

        public override string formatData(PM pm)
        {
            //反馈信息
            String result = String.Empty;
            String Empty = "NULL";
            NYBG_PM nybg = (NYBG_PM)pm;

            nybg.zz = GlobalMethod.Semicolon(nybg.zz);
            nybg.zzdw = GlobalMethod.Semicolon(nybg.zzdw);
            nybg.zbdw = GlobalMethod.Semicolon(nybg.zbdw);
            nybg.ztc = GlobalMethod.Semicolon(nybg.ztc);
            nybg.zfl = GlobalMethod.Semicolon(nybg.zfl);
            nybg.wjm = "自动生成";
            nybg.dlr = user.name;
            nybg.gxrq = DateTime.Now;
            nybg.sybm = nybg.flbm + "-" + nybg.nf.ToString();

            if (nybgDAO.GetNYBG_FLByFlbm(nybg.flbm) == null)
            {
                result += "分类编码" + nybg.flbm + "不存在 ";
            }
            if (Empty.Equals(nybg.ywjm))
            {
                result += "原文件名（PDF全文）为空 ";
                nybg.qw = false;
            }
            else
            {
                if (!File.Exists(fileFolder + nybg.ywjm))
                {
                    result += nybg.ywjm + " PDF文件不存在";
                    nybg.qw = false;
                }
                else
                {
                    nybg.qw = true;
                    PdfReader pdf = new PdfReader(fileFolder + nybg.ywjm);
                    if (null != pdf)
                    {
                        nybg.ys = pdf.NumberOfPages;
                    }
                    else
                    {
                        nybg.ys = 0;
                    }
                    pdf.Close();
                }
            }
            if (Empty.Equals(nybg.bgmc))
            {
                result += "报告名称为空 ";
            }
            if (nybg.nf == 0)
            {
                result += "年份为空 ";
            }

            if (!result.Equals(String.Empty))
            {
                result += " : " + nybg.nf + "年" + nybg.zz + "《" + nybg.bgmc + "》\n";
            }

            return result;
        }

        public override String insertPM(PM pm)
        {
            NYBG_PM nybg = (NYBG_PM)pm;
            int back;
            String err = String.Empty;
            //打开连接
            this.openOleDbConnection();
            OleDbCommand sqlcmd = new OleDbCommand();
            if (!String.Empty.Equals(validateTableName(formatPmTableName)))
            {
                sqlcmd.CommandText = @"create Table " + formatPmTableName + @"(分类编码 char(10), 索引编码 char(50), 文件名 char(30), 页数 smallInt, 报告名称 char(255), 年份 char(4), 出版日期 datetime, 作者 char(254), 作者单位 char(200), 主办单位 text, 主题词 char(200), 文摘 text, 报告号 char(50), 分类体系 char(10), 子分类 char(200), 文献编号 char(30), 原文件名 char(255), 全文 boolean, 更新日期 datetime, 登录人 char(4))";
                sqlcmd.Connection = this.ObjConnection;
                try
                {
                    back = sqlcmd.ExecuteNonQuery();
                }
                catch (Exception e)
                {
                    err = e.Message + "\n";
                    return err;
                }
            }

            sqlcmd.CommandText = @"insert into " + formatPmTableName + @"(分类编码,索引编码,文件名,页数,报告名称,年份,出版日期,作者,作者单位,主办单位,主题词,文摘,报告号,分类体系,子分类,文献编号,原文件名,全文,更新日期) values(@分类编码,@索引编码,@文件名,@页数,@报告名称,@年份,@出版日期,@作者,@作者单位,@主办单位,@主题词,@文摘,@报告号,@分类体系,@子分类,@文献编号,@原文件名,@全文,@更新日期)";
            sqlcmd.Connection = this.ObjConnection;
            sqlcmd.Parameters.Add(new OleDbParameter("分类编码", nybg.flbm));
            sqlcmd.Parameters.Add(new OleDbParameter("索引编码", nybg.sybm));
            sqlcmd.Parameters.Add(new OleDbParameter("文件名", nybg.wjm));
            sqlcmd.Parameters.Add(new OleDbParameter("页数", nybg.ys));
            sqlcmd.Parameters.Add(new OleDbParameter("报告名称", nybg.bgmc));
            sqlcmd.Parameters.Add(new OleDbParameter("年份", nybg.nf));
            sqlcmd.Parameters.Add(new OleDbParameter("出版日期", nybg.cbrq));
            sqlcmd.Parameters.Add(new OleDbParameter("作者", nybg.zz));
            sqlcmd.Parameters.Add(new OleDbParameter("作者单位", nybg.zzdw));
            sqlcmd.Parameters.Add(new OleDbParameter("主办单位", nybg.zbdw));
            sqlcmd.Parameters.Add(new OleDbParameter("主题词", nybg.ztc));
            sqlcmd.Parameters.Add(new OleDbParameter("文摘", nybg.wz));
            sqlcmd.Parameters.Add(new OleDbParameter("报告号", nybg.bgh));
            sqlcmd.Parameters.Add(new OleDbParameter("分类体系", nybg.fltx));
            sqlcmd.Parameters.Add(new OleDbParameter("子分类", nybg.zfl));
            sqlcmd.Parameters.Add(new OleDbParameter("文献编号", nybg.wxbh));
            sqlcmd.Parameters.Add(new OleDbParameter("原文件名", nybg.ywjm));
            sqlcmd.Parameters.Add(new OleDbParameter("全文", nybg.qw));
            OleDbParameter parameter = new OleDbParameter("更新日期", OleDbType.DBDate);
            parameter.Value = nybg.gxrq;
            sqlcmd.Parameters.Add(parameter);
            try
            {
                back = sqlcmd.ExecuteNonQuery();
            }
            catch (Exception e)
            {
                err = e.Message + "\n";
            }
            sqlcmd.Parameters.Clear();

            this.closeOleDbConnection();
            return err;
        }

        public override int deletePM(PM pm, out String err)
        {
            int back = 0;
            err = String.Empty;
            NYBG_PM nybg = (NYBG_PM)pm;
            //打开连接
            this.openOleDbConnection();
            OleDbCommand sqlcmd = new OleDbCommand();
            if (!String.Empty.Equals(validateTableName(formatPmTableName)))
            {
                sqlcmd.CommandText = @"create Table " + formatPmTableName + @"(分类编码 char(10), 索引编码 char(50), 文件名 char(30), 页数 smallInt, 报告名称 char(255), 年份 char(4), 出版日期 datetime, 作者 char(254), 作者单位 char(200), 主办单位 text, 主题词 char(200), 文摘 text, 报告号 char(50), 分类体系 char(10), 子分类 char(200), 文献编号 char(30), 原文件名 char(255), 全文 boolean, 更新日期 datetime, 登录人 char(4))";
                sqlcmd.Connection = this.ObjConnection;
                try
                {
                    back = sqlcmd.ExecuteNonQuery();
                }
                catch (Exception e)
                {
                    err = e.Message + "\n";
                    return 0;
                }
            }
            //sql语句
            sqlcmd.CommandText = @"delete from " + formatPmTableName + " where 索引编码=@索引编码 and 年份=@年份 and 报告名称=@报告名称";
            sqlcmd.Connection = this.ObjConnection;
            sqlcmd.Parameters.Add(new OleDbParameter("索引编码", nybg.sybm));
            sqlcmd.Parameters.Add(new OleDbParameter("年份", nybg.nf));
            sqlcmd.Parameters.Add(new OleDbParameter("报告名称", nybg.bgmc));

            try
            {
                back = sqlcmd.ExecuteNonQuery();
            }
            catch (Exception e)
            {
                err = "Exception: " + e.Message + "\n";
            }
            sqlcmd.Parameters.Clear();
            //            this.closeOleDbConnection();
            return back;
        }
        /* 现在的方法先delete再insert，就不用为每文库写update了
        public override bool updatePM(PM pm)
        {
            ZWQK_PM zwqk = (ZWQK_PM)pm;
            //打开连接
            this.openOleDbConnection();

            //sql语句
            OleDbCommand sqlcmd = new OleDbCommand(@"update ZWQK set 作者=@作者,作者单位=@作者单位,中文主题词=@中文主题词,外文主题词=@外文主题词,国图分类=@国图分类 where 中文篇名=@中文篇名 and 文件名=@文件名", this.ObjConnection);

            sqlcmd.Parameters.Add(new OleDbParameter("作者", zwqk.zz));
            sqlcmd.Parameters.Add(new OleDbParameter("作者单位", zwqk.zzdw));
            sqlcmd.Parameters.Add(new OleDbParameter("中文主题词", zwqk.zwztc));
            sqlcmd.Parameters.Add(new OleDbParameter("外文主题词", zwqk.wwztc));
            sqlcmd.Parameters.Add(new OleDbParameter("国图分类", zwqk.gtfl));
            sqlcmd.Parameters.Add(new OleDbParameter("中文篇名", zwqk.zwpm));
            sqlcmd.Parameters.Add(new OleDbParameter("文件名", zwqk.wjm));
            int back = sqlcmd.ExecuteNonQuery();
            if (back == 0)
            {
                return false;
            }
            //objConnection.Close();
            return true;
        }*/

        public override bool findServerDuplicate(PM pm)
        {
            NYBG_PM nybg = (NYBG_PM)pm;
            IList<NYBG_PM> result = nybgDAO.QueryNybgPM(nybg.sybm, nybg.nf.ToString(), nybg.bgmc);
            if (result != null && result.Count != 0)
                return true;
            else
                return false;
        }

        public override String insertPMwithUpdateWJM(PM pm)
        {
            String err = String.Empty;
            NYBG_PM nybg = (NYBG_PM)pm;
            int index;
            index = nybg.ywjm.LastIndexOf('/');
            int serial;
            if ("ml".Equals(nybg.ywjm.Substring(index + 1, 2)))
            {
                serial = 0;
            }
            else
            {

                NYBG_PM maxPm = nybgDAO.getMaxNYBG_PM(nybg.flbm, nybg.nf.ToString());
                if (maxPm != null)
                {
                    int pos = maxPm.wjm.LastIndexOf('-');
                    int pos2 = maxPm.wjm.LastIndexOf('.');
                    serial = int.Parse(maxPm.wjm.Substring(pos + 1, 4)) + 1;
                }
                else
                {
                    serial = 1;
                }
            }
            index = nybg.ywjm.LastIndexOf('.');
            String suffixStr;
            if (index >= 0)
                suffixStr = nybg.ywjm.Substring(index);
            else
                suffixStr = String.Empty;
            String serialStr = "0000" + serial.ToString();
            nybg.wjm = nybg.sybm + "-" + serialStr.Substring(serialStr.Length - 4) + suffixStr;
            try
            {
                nybgDAO.InsertNYBG_PM(nybg);
            }
            catch (Exception e)
            {
                err += e.Message + "\n";
            }
            return err;
        }

        public override string addOneRecord(PM pm)
        {
            String err = String.Empty;
            NYBG_PM nybg = (NYBG_PM)pm;
            nybg.gxrq = DateTime.Now;
            nybg.eraseNullInEmptyString();
            err += insertPMwithUpdateWJM(pm);
            if (!String.Empty.Equals(err))
                return err;
            String path = "NYBG/";
            path += nybg.sybm.Substring(0, 2) + "/";
            path += nybg.sybm.Substring(2, 2) + "/";
            path += nybg.sybm.Substring(4, 2) + "/";
            path += nybg.nf.ToString() + "/";

            String srcFile = fileFolder + nybg.ywjm;
            String destFile = path + nybg.wjm;
            try
            {
                FTPtransfer.uploadAndCreateDir(destFile, srcFile);
                System.IO.File.Delete(srcFile);
            }
            catch (Exception e)
            {
                err += "Exception: " + e.Message + ",FTP文件传输失败\n";
                nybgDAO.DeleteNYBG_PM(nybg.wjm, user.name);
            }
            return err;
        }

    }
}
